package com.fowo.api.tiktok.util;


import cn.hutool.core.util.StrUtil;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.DataTypeKind;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

public class TiktokUtil {

    public static BaseAspect getBaseAspect() {
        return new BaseAspect(DataTypeKind.TIKTOK.getValue());
    }

    public static String getSign(String appSecret, String urlPath, Map<String,Object> query, String body){
        query.remove("access_token");
        StringBuilder input = new StringBuilder();
        for(String key : query.keySet()){
            input.append(key).append(query.get(key));
        }
        String toSign = "";
        if(StrUtil.isNotBlank(body)){
            toSign = appSecret+urlPath + input.toString() + body + appSecret;
        }else {
            toSign = appSecret + urlPath + input.toString() + appSecret;
        }
        String hashValue = hmacSha256(toSign, appSecret);
        return hashValue;
    }

    public static String hmacSha256(String message, String secret) {
        String hash = "";
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(message.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hash;
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String tmp;
        for (int n = 0; b != null && n < b.length; n++) {
            tmp = Integer.toHexString(b[n] & 0XFF);
            if (tmp.length() == 1) {
                hs.append('0');
            }
            hs.append(tmp);
        }
        return hs.toString().toLowerCase();
    }

    public static Date secondToDate(Long second){
        if(second != null){
            Date date = new Date(second * 1000L);
            //转成北京时间
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(date);
//            calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
//            calendar.getTime();
            return date;
        }
       return null;
    }

}
